<template>
	<view class="config">
 
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					当前学期：
				</view>
				<view class="uni-list-cell-db">
						<picker @change="bindTermChange" :value="termIndex" :range="termArray" range-key="name">
							<view class="uni-input">{{termArray[termIndex].name}}</view>
						</picker>
				</view>
			</view>
 
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					学期开始：
				</view>
				<view class="uni-list-cell-db">
					<picker mode="date" :value="sdate"  @change="bindSDateChange">
						<view class="uni-input">{{sdate}}</view>
					</picker>
				</view>
			</view>
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					学期结束：
				</view>
				<view class="uni-list-cell-db">
					<picker mode="date" :value="edate" @change="bindEDateChange">
						<view class="uni-input">{{edate}}</view>
					</picker>
				</view>
			</view>
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					学期课程：
				</view>
				<view class="uni-list-cell-db">
					<view class="text addCourse" @click="doAdd">新增</view>
				</view>
			 </view>	
			<view class="uni-list-cell">
				<view class="uni-list-cell-db myTable">
		<!-- 			<view class="uni-flex uni-row myheader" style="-webkit-justify-content: space-between;justify-content: space-between;display:flex">
						<view class="text">
						</view>
						<view class="text addCourse" @click="doAdd">新增
						</view>
					</view> -->
			         <uni-table border stripe emptyText="暂无数据"  >
							<!-- 表头行 -->
							<uni-tr>
							<!-- 	<uni-th  align="center">课程ID</uni-th> -->
								<uni-th  align="center">课程名称</uni-th>
								<uni-th  align="center">设置</uni-th>
							</uni-tr>
							<!-- 表格数据行 -->
							<uni-tr v-for="(item,index) in courseList" :key="index">
								<!-- <uni-td align="center">{{item.value}}</uni-td> -->
								<uni-td align="center">{{item.text}}</uni-td>
								<uni-td align="center">
										<view class="uni-group" >
											<button class="uni-button" size="mini" type="primary" @click="doModify(index)">修改</button>
											&nbsp;&nbsp;&nbsp;&nbsp;
											<button class="uni-button" size="mini" type="warn"  @click="doDelete(index)">删除</button>
										</view>
								</uni-td>					
							</uni-tr>
					</uni-table>
				</view>  	
            </view>		   
			<view class="uni-btn-v">
				<button type="primary" class="btn" @tap="doSaveTerm">保 存</button>
				<button type="default" class="btn" @tap="goCtable" >返 回</button>
			</view>		
		</view>
		

		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog ref="inputClose"  mode="input" title="输入内容" :modelValue="courseName"
					placeholder="请输入课程名称" @confirm="dialogInputConfirm"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	function getToday(type) {
		const date = new Date();

		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();

		if (type === 'start') {
			year = year - 10;
		} else if (type === 'end') {
			year = year + 10;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;

		return `${year}-${month}-${day}`;
	}	
	function randomString(length) {
	      const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	      let result = '';
	      for(let i = 0; i<length; i++)
	      {
	        let id = Math.floor(Math.random() * str.length);
	        result += str[id];
	      }
	      return result;
	}
	export default {
		data() {
			return {
				sdate:getToday({
					format: true
				}),
				edate:getToday({
					format: true
				}),
				courseIndex:0,
				courseId:'',
				courseName:'',
				courseList:[],
				termIndex:0,
				termArray:[{name:'第一学期'},{name: '第二学期'}, {name:'第三学期'}, {name:'第四学期'},{name:'第五学期'},{name: '第六学期'}, {name:'第七学期'}, {name:'第八学期'}]
			}
		},
		onLoad() {
			this.loadTermStorage();
		},		
		methods: {
			goCtable(){
				uni.navigateTo({
				  url: '../ctable/ctable' // 跳转到对应路径的页面
				});
			},
			doSaveTerm(){
				// 创建Date对象
				var date1 = new Date(this.sdate);
				var date2 = new Date(this.edate);
				// 获取时间戳
				var timestamp1 = date1.getTime();
				var timestamp2 = date2.getTime();				
				if (timestamp1>=timestamp2){
					uni.showModal({
							title: '学期开始时间必须小于结束时间!',
							showCancel:false
					})
					return;
				}
				if (this.courseList.length==0){
					uni.showModal({
							title: '请新增课程信息，课程列表不能为空!',
							showCancel:false
					})
					return;
				}
				uni.showLoading({
					title: '正在保存'
				})				
				setTimeout(() => {
					uni.hideLoading()
                    let termData = {"sdate":this.sdate,"edate":this.edate,"courseList":this.courseList} ;
					console.log(termData);
					this.setStorage("termData"+this.termIndex,termData); 
					this.setStorage("termIndex",this.termIndex); 
			        //uni.navigateTo({
			        //  url: '../ctable/ctable' // 跳转到对应路径的页面
			        //});
					this.goCtable();
				   
				}, 1000); 
			},
			doAdd(){
				this.courseId=null;
				this.courseName=null;
				this.$refs.inputDialog.open()
			},
			doModify(index){
				this.courseIndex=index;
				this.courseId=this.courseList[index].value;
				this.courseName=this.courseList[index].text;
				console.log("courseName",this.courseName);
				this.$refs.inputDialog.open()
			},
			doDelete(index){
				uni.showModal({
					title: '提示',
					content: '删除后，已有课程表的课程数据无法正常显示！确定删除?',
					success: res => {
						if (res.confirm) {
						this.courseList.splice(index, 1);
						}
					}
				});				
				
			},	
			dialogInputConfirm(val) {
				uni.showLoading({
					title: '正在保存'
				})

				setTimeout(() => {
					uni.hideLoading()
					console.log(val)
				    if (this.courseId==null){
						let id =  randomString(4);
						let course={"value":id,"text":val};
						this.courseList.push(course);
					}else{
						this.courseList[this.courseIndex].text=val;
					}
					
					// 关闭窗口后，恢复默认内容
					this.$refs.inputDialog.close()
				}, 100)
			},			
			bindTermChange(e){
				this.termIndex=e.detail.value;
				this.loadTermData();
			},
			bindSDateChange(e){
				this.sdate = e.detail.value
			},
			bindEDateChange(e){
				this.edate = e.detail.value
			},
			loadTermStorage: function () {
				let key ="termIndex";				
				uni.getStorage({
					key: key,
					success: (res) => {
						this.termIndex= res.data;
						this.loadTermData();
					},
					fail: () => {
						this.termIndex=0;
					}
				})
				 
			},
		    loadTermData: function () {
				let key ="termData"+this.termIndex;
				uni.getStorage({
					key: key,
					success: (res) => {
						console.log(res.data)
						let termData= res.data;	
						this.sdate= termData.sdate;
						this.edate= termData.edate;
						this.courseList= (termData.courseList)?termData.courseList:[];
					},
					fail: () => {
						this.sdate=getToday({
							format: true
						});
						this.edate=getToday({
						 	format: true
						}); 
						this.courseList =[];
					}
				})	 
			},			
			setStorage: function (key,data) {		
				uni.setStorage({
					key: key,
					data: data,
					success: (res) => {
						// uni.showModal({
						// 	title: '存储数据成功',
						// 	showCancel:false
						// })
					},
					fail: () => {
						uni.showModal({
							title: '储存数据失败!',
							showCancel:false
						})
					}
				})
				
			},
			clearStorage: function () {
				uni.showModal({
					title: '提示',
					content: '确定清除所有数据吗?',
					success: res => {
						if (res.confirm) {
							uni.clearStorageSync();
							uni.showModal({
								title: '清除数据成功',
								showCancel:false
							})
						}
					}
				});						
			}
		}
	}
</script>

<style>
	.config{
		padding: 15rpx;
	}
	.addCourse{
		padding: 15rpx;
	}
	.btn {
		padding: 10rpx;
	}
    .myTable{
		padding: 15rpx;
	}
</style>
